package com.deyuanyun.pic.settings.controller;

import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.security.ClientUtil;
import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.ResponseUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.settings.controller.dto.UserSessionVO;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyLogoVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserVO;
import com.deyuanyun.pic.settings.domain.base.BizMsgUser;
import com.deyuanyun.pic.settings.domain.prvlg.CustomUser;
import com.deyuanyun.pic.settings.domain.prvlg.User;
import com.deyuanyun.pic.settings.service.base.BizMsgSendService;
import com.deyuanyun.pic.settings.service.org.CompanyService;
import com.deyuanyun.pic.settings.service.prvlg.MenuService;
import com.deyuanyun.pic.settings.service.prvlg.UserService;
import com.deyuanyun.pic.settings.support.SecurityUtils;
import com.deyuanyun.pic.settings.support.cache.TempStoreDataSupport;
import com.deyuanyun.pic.settings.support.exception.NoRoleException;
import com.github.pagehelper.SqlUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Controller
@RequestMapping("/")
public class IndexController extends AbstractBaseController {

    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;
    @Resource
    private Producer captchaProducer;

    @Resource
    private CompanyService companyService;

    //added by axiao
    @Autowired
    private BizMsgSendService bizMsgSendService;//当前用户消息相关的service


    @RequestMapping("/index")
    public String index(Model model) {
        return "/login";
    }

    @RequestMapping("/loginout")
    public void loginout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SecurityUtils.removeUser(request);
        org.apache.shiro.SecurityUtils.getSubject().logout();
        request.getSession().invalidate();
        response.sendRedirect("login.html");
        // return new ModelAndView("redirect:login.html");
    }


    @ResponseBody()
    @RequestMapping("/clientLogin.html")
    public void clientLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        password = ClientUtil.encodePassword(userName, password);
        if(StringUtils.isEmpty(userName))
        {
            ResponseUtil.printl(response, "{\"status\":-1,\"msg\":\"账户不能为空\"}", "text");
            return;
        }
        if(StringUtils.isEmpty(password))
        {
            ResponseUtil.printl(response, "{\"status\":-1,\"msg\":\"密码不能为空\"}", "text");
            return;
        }
        List<CustomUser> userList = null;
        try {
            userList = userService.getUser(userName);

        } catch (Exception e) {
            logger.error("", e);
        }
        if (ObjectUtil.isEmptyAll(userList)) {
            ResponseUtil.printl(response, "{\"status\":-1,\"msg\":\"没有用户\"}", "text");
//            throw new AuthenticationException("没有用户");
        }
        if (!"ACTIVATE".equals(userList.get(0).getState())) {
            ResponseUtil.printl(response, "{\"status\":-1,\"msg\":\"帐户已被禁用\"}", "text");
//            throw new DisabledAccountException("帐户已被禁用");
        }
        if (password.equals(userList.get(0).getPwd())) {
            CompanyLogoVO companyLogoVO =companyService.getUserTopCompanyLogo(userName);
            UserVO userVO = null;
            try {
               userVO =userService.queryUserExpById(userList.get(0).getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            ResponseUtil.printl(response, "{\"status\":0,\"msg\":\"登录成功\",\"realName\":\""+userVO.getRealName()+"\",\"companyName\":\""+companyLogoVO.getName()+"\"}", "text");

        } else {
            ResponseUtil.printl(response, "{\"status\":-1,\"msg\":\"登录失败\"}", "text");

        }


    }

    @RequestMapping("/login")
    public String login(Model model, User inUser, HttpServletRequest request,
                        @RequestParam(value = "rememberMe", required = false, defaultValue = "false") Boolean rememberMe,
                        HttpServletResponse response) throws IOException {
//        String validCode=request.getParameter("validCode");
//        String sessionCode=request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
//        if (!StringUtils.(sessionCode, validCode)){
//            model.addAttribute("errorMessage", "验证码错误");
//            return "/index";
//        }

//        UserSessionVO user = SecurityUtils.currentUserSessionVO();
//        if (user!=null){
//            SecurityUtils.removeUser(request);
//            org.apache.shiro.SecurityUtils.getSubject().logout();
////            response.sendRedirect("login.html");
//            return "/login";
//        }
        boolean f = org.apache.shiro.SecurityUtils.getSubject().isRemembered();

        if (StringUtils.isEmpty(inUser.getUsername())) {
            if ((request.getSession().getAttribute("isAccessed_") == null)) {
                request.getSession().setAttribute("isAccessed_", "yes");
                return "/login";
            } else {
                model.addAttribute("errorMessage", "请填写用户名");
                return "/login";
            }

        }
        if (StringUtils.isEmpty(inUser.getPwd())) {
            model.addAttribute("errorMessage", "请填写密码");
//            Asserts.assertTrue(false, "sds");
            return "/login";
        }

        Subject suser = org.apache.shiro.SecurityUtils.getSubject();
        String enPwd = SecurityUtils.encodePassword(inUser.getUsername(), inUser.getPwd());
        //enPwd="aaa";
        UsernamePasswordToken token = new UsernamePasswordToken(inUser.getUsername(), enPwd, rememberMe);
        try {
            suser.login(token);
        } catch (NoRoleException roleEx) {
            model.addAttribute("errorMessage", roleEx.getMessage());
            org.apache.shiro.SecurityUtils.getSubject().logout();
            return "/login";
        } catch (DisabledAccountException e1) {
            model.addAttribute("errorMessage", "帐户已经被禁用");
            org.apache.shiro.SecurityUtils.getSubject().logout();
            return "/login";
        } catch (AuthenticationException e) {
            model.addAttribute("errorMessage", "用户名或密码错误!");
            org.apache.shiro.SecurityUtils.getSubject().logout();
            return "/login";
        }


        //密码处理类
       /* String enPwd=SecurityUtils.encodePassword(inUser.getUsername(),inUser.getPwd());
        if (StringUtils.isEmpty(inUser.getPwd())
                || !enPwd.equals(userList.get(0).getPwd())){
        *//*if (StringUtils.isEmpty(inUser.getPwd())
                || !inUser.getPwd().equals(userList.get(0).getPwd())) {*//*
            model.addAttribute("errorMessage", "用户名或密码错误");
            return "/login";
            //todo 还未加密
        }*/

        //SecurityUtils.setUser(userList.get(0));
        //UserSessionVO sessionVO= SecurityUtils.currentUserSessionVO();
        UserSessionVO user1 = SecurityUtils.currentUserSessionVO();
        //List<Menu> menuList = menuService.getRootMenu(user.getUsername());
        //request.getSession().setAttribute("menuList", menuList);
        request.getSession().setAttribute("username", user1.getUsername());
        //return "/home";

        Properties props = TempStoreDataSupport.pullDataf("application.properties");
        String url = Globals.getProperties("afterLoginedUrl");
        return "redirect:" + url;
    }

    @RequestMapping("/toHome")
    public String home(Model model) {
        UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //UserSessionVO sessionVO= SecurityUtils.currentUserSessionVO();
        model.addAttribute("username", user.getUsername());
        return "/home_new";
    }

    @RequestMapping("/toMain")
    public String main(Model model) {
        UserSessionVO user = SecurityUtils.currentUserSessionVO();
        model.addAttribute("username", user.getUsername());
        return "/main";
    }

    /**
     * 基础数据
     *
     * @param model
     * @return
     */
    @RequestMapping("/basedata/toMain")
    public String baseMain(Model model) {
        //UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //model.addAttribute("username", user.getUsername());
        //return "/basedata/main";
        return "redirect:/pipe/pipeLineInfo/toPipeLineInfo.html";
    }

    @RequestMapping("/insp/toMain")
    public String inspMain(Model model) {
        UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //model.addAttribute("username", user.getUsername());
        //return "/insp/main";
        return "redirect:/insp/metalLoss.html";
    }

    /***
     * 清理
     *
     * @param model
     * @return
     */
    @RequestMapping("/pig/toMain")
    public String pigMain(Model model) {
        //UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //model.addAttribute("username", user.getUsername());
        //return "/pig/main";
        return "redirect:/cleanTask/cleanPipeLineHistory/getCleanPipeLineHistoryIndex.html";
    }

    @RequestMapping("/risk/toMain")
    public String riskMain(Model model) {
        //UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //model.addAttribute("username", user.getUsername());
        //return "/risk/main";
        return "redirect:/risk/assessment/toriskdatails.html";
    }

    @RequestMapping("/settings/toMain")
    public String settingsMain(Model model) {
        //UserSessionVO user = SecurityUtils.currentUserSessionVO();
        // model.addAttribute("username", user.getUsername());
        // return "/settings/main";
        return "redirect:/settings/org/company/page.html";
    }

    @RequestMapping("/validCode")
    public void validCode(HttpServletResponse response, HttpServletRequest request) {
        ServletOutputStream out = null;
        try {
            response.setDateHeader("Expires", 0);
            // Set standard HTTP/1.1 no-cache headers.
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            // Set standard HTTP/1.0 no-cache header.
            response.setHeader("Pragma", "no-cache");
            // return a jpeg
            response.setContentType("image/jpeg");
            // create the text for the image
            String capText = captchaProducer.createText();
            // store the text in the session
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
            // create the image with the text
            BufferedImage bi = captchaProducer.createImage(capText);
            out = response.getOutputStream();
            // write the data out
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("newTest.json")
    @ResponseBody
    public void newTest() {
        //Asserts.assertTrue(false,"jjjjjjj");
        // PageJsonBean jsonBean=new PageJsonBean();
        List<UserSessionVO> l = new ArrayList<UserSessionVO>();
        UserSessionVO m = new UserSessionVO();
        m.setUsername("ccc");
        m.setEmail("vvvv");
        l.add(m);
        UserSessionVO m1 = new UserSessionVO();
        m1.setUsername("ccc1");
        m1.setEmail("vvvv1");
        l.add(m1);
        UserSessionVO m2 = new UserSessionVO();
        m2.setUsername("ccc12");
        m2.setEmail("vvvv12");
        l.add(m2);
        UserSessionVO m3 = new UserSessionVO();
        m3.setUsername("ccc123");
        m3.setEmail("vvvv123");
        l.add(m3);
        UserSessionVO m4 = new UserSessionVO();
        m4.setUsername("ccc124");
        m4.setEmail("vvvv124");
        l.add(m4);
        UserSessionVO user = SecurityUtils.currentUserSessionVO();
        //PageHelper.startPage(1,1);
        SqlUtil.clearLocalPage();
        //  List<Menu> menuList = menuService.getRootMenu(user.getUsername());
        PageJsonBean jsonBean = new PageJsonBean();
        //List<Menu> menuList1 = menuService.getRootMenu(user.getUsername());

        jsonBean.setList(l);
        jsonBean.setTotal(100);
        jsonBean.setPageNum(5);
        jsonBean.setPageCount(1);
        //jsonBean.setTotal((int)((Page)menuList).getTotal());
        //jsonBean.setTotal(20);

        //Subject suser = org.apache.shiro.SecurityUtils.getSubject();

        //SessionCacheSupport.get((String) suser.getSession().getId());
        //SessionCacheSupport.getOnlineUser();

        AjaxSupport.sendSuccessText("vvv", jsonBean);
    }


    /**
     * 得到用户的消息列表
     *
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-07-08
     */
    @RequestMapping("/getUserMsg.json")
    @ResponseBody
    public void getUserMsgList(HttpServletResponse response) {
        PageJsonBean jsonBean = new PageJsonBean();
        List<BizMsgUser> list = bizMsgSendService.queryMsgListByUser();
        jsonBean.setList(list);
        AjaxSupport.sendSuccessText("success", "yyyy.MM.dd", jsonBean, "id", "createDate", "msgContent", "readed", "handled");
    }


}
